package com.hk.core.autoconfigure.weixin.cp;

import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author Kevin
 * 企业微信自动配置
 */
@AutoConfiguration
@ConditionalOnClass(WxCpService.class)
@ConditionalOnProperty(prefix = "wx.cp", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(WeiXinCpProperties.class)
public class WeiXinCpConfiguration {

    private final WeiXinCpProperties weiXinCpProperties;

    private static Map<Integer, WxCpService> cpServices;

    public WeiXinCpConfiguration(WeiXinCpProperties weiXinCpProperties) {
        this.weiXinCpProperties = weiXinCpProperties;
        cpServices = this.weiXinCpProperties.getAppConfigs().stream().map(config -> {
            var configStorage = new WxCpDefaultConfigImpl();
            configStorage.setCorpId(this.weiXinCpProperties.getCorpId());
            configStorage.setAgentId(config.getAgentId());
            configStorage.setCorpSecret(config.getSecret());
            configStorage.setToken(config.getToken());
            configStorage.setAesKey(config.getAesKey());
            var service = new WxCpServiceImpl();
            service.setWxCpConfigStorage(configStorage);
            return service;
        }).collect(Collectors.toMap(service -> service.getWxCpConfigStorage().getAgentId(), Function.identity()));
    }

    public static Optional<WxCpService> getCpService(Integer agentId) {
        return Optional.ofNullable(cpServices.get(agentId));
    }
}
